<?php

namespace app\api\controller\v1\posts;

use app\api\controller\v1\wechat\AuthController;
use app\Request;
use app\services\posts\PostLikeServices;
use app\services\posts\PostsServices;

/**
 * 帖子点赞
 */
class PostLikeController extends AuthController
{
    /**
     * @var PostLikeServices
     */
    protected $service;

    /**
     * PostLikeServices constructor.
     * @param PostLikeServices $services
     */
    public function __construct(PostLikeServices $services)
    {
        $this->service = $services;
    }

    /**
     * 帖子点赞
     * @param Request $request
     * @return mixed
     */
    public function like(Request $request) {
        $where = $request->postMore([
            ['post_id', 0]
        ]);
        $where['user_id'] = $request->uid();
        $where['add_time'] = time();

        $like = $this->service->getOne(['post_id' => $where['post_id'], 'user_id' => $where['user_id']]);
        /** @var PostsServices $postsServices */
        $postsServices = app()->make(PostsServices::class);
        $posts = $postsServices->getOne(['id' => $where['post_id']]);
        // 不存在点赞，则点赞
        if (!isset($like)){
            $this->service->save($where);
            $postsServices->update($posts['id'], ['like_count' => $posts['like_count'] + 1]);
            return app("json")->success('点赞成功');
        }
        // 存在点赞，则取消点赞
        else {
            $this->service->delete($like['id']);
            $postsServices->update($posts['id'], ['like_count' => $posts['like_count'] - 1]);
            return app("json")->success('取消点赞成功');
        }

    }

}